package com.sservice.web.controller.pc;

import com.sservice.banfu.mapper.SalePersonMapper;
import com.sservice.banfu.vo.SalePersonVo;
import com.sservice.common.Constants;
import com.sservice.common.SameUrlData;
import com.sservice.model.dao.IAddressDao;
import com.sservice.model.vo.ClienteleVo;
import com.sservice.model.vo.OrderVo;
import com.sservice.service.service.*;
import com.sservice.base.entity.dto.BaseResult;
import com.sservice.base.entity.dto.ListResult;
import com.sservice.base.entity.dto.Pagination;
import com.sservice.model.entity.Address;
import com.sservice.model.entity.Clientele;
import com.sservice.model.entity.Goods;
import com.sservice.banfu.e.SalePerson;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpSession;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

@Controller
@RequestMapping("/clientele")
public class ClientelePcController {
    @Autowired
    IClienteleService dataService;
    @Autowired
    ISalePersonService spService;
    @Autowired
    IGoodsService goodsService;
    @Autowired
    IOrderService orderService;
    @Autowired
    SalePersonMapper salePersonMapper;
    @Autowired
    IAddressDao addressDao;
    @Autowired
    AddressService addressService;
    private Logger logger = LoggerFactory.getLogger(this.getClass());

    /**
     * 创建
     *
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/get", method = RequestMethod.GET)
    public BaseResult<Clientele> get(Clientele arg) {
        Clientele service_res = dataService.selectByPrimaryKey(arg.getId());
        BaseResult<Clientele> res = new BaseResult<Clientele>(true, service_res);
        return res;
    }

    /***
     * 申请供应商
     * @param clientele 汇款资料
     * @return
     */
    @SameUrlData
    @ResponseBody
    @RequestMapping(value = "/provider", method = RequestMethod.POST)
    public BaseResult provider(Clientele clientele) {
        int service_res = 0;
        Clientele clientele1 = new Clientele();
        clientele1.setId(clientele.getId());
        clientele1.setBank(clientele.getBank());
        clientele1.setType("1");// 供应商
        clientele1.setBankAccount(clientele.getBankAccount());
        clientele1.setRemitInfo(clientele.getRemitInfo());
        clientele1.setSupplierCheckStatus("0"); // 审核中
        int res = dataService.updateByPrimaryKeySelective(clientele1);
        return new BaseResult(true, String.valueOf(res), 200);
    }

    /**
     * 增加地址
     *
     * @param address
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/address", method = RequestMethod.POST)
    public BaseResult get(Address address) {
        int service_res = 0;
        if (address.getId() != null) {
            service_res = addressDao.updateByPrimaryKeySelective(address);
        } else {
            service_res = addressDao.insertSelective(address);
        }

        return new BaseResult(true, String.valueOf(service_res), 200);
    }

    /***
     * 开票资料
     * @param c
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/paper", method = RequestMethod.POST)
    public BaseResult paper(Clientele c) {
        Clientele clientele = new Clientele();
        clientele.setId(c.getId());
        clientele.setPaperAccount(c.getPaperAccount());
        clientele.setPaperAddress(c.getPaperAddress());
        clientele.setPaperBank(c.getPaperBank());
        clientele.setPaperTel(c.getPaperTel());
        int service_res = 0;
        service_res = dataService.updateByPrimaryKeySelective(clientele);
        return new BaseResult(true, String.valueOf(service_res), 200);
    }

    @ResponseBody
    @RequestMapping(value = "/address/{ownerid}", method = RequestMethod.GET)
    public ListResult query(Address address) {
        Address address1 = new Address();
        address1.setStatus("1");
        address1.setOwnerid(address.getOwnerid());
        List<Address> list = addressDao.select(address1);
        return new ListResult(true, list);
    }

    @ResponseBody
    @SameUrlData
    @RequestMapping(value = "/set/patch", method = RequestMethod.POST)
    public BaseResult setpatch(Address address) {
        addressService.setDefault(address);
        addressService.setReceive(address);
        addressService.setPaper(address);
        return new BaseResult(true, "success", 200);
    }

    @ResponseBody
    @RequestMapping(value = "/set/{remark1}/{id}/{default_}", method = RequestMethod.POST)
    public BaseResult set(Address address) {
        int service_res = 0;
        if (address.getRemark1().equals("default_")) {
            service_res = addressService.setDefault(address);
        }
        if (address.getRemark1().equals("receive")) {
            service_res = addressService.setReceive(address);
        }
        if (address.getRemark1().equals("paper")) {
            service_res = addressService.setPaper(address);
        }
        if (address.getRemark1().equals("status")) {
            Address a = new Address();
            a.setStatus(address.getDefault_());
            a.setId(address.getId());
            service_res = addressDao.updateByPrimaryKeySelective(a);
        }
        return new BaseResult(true, String.valueOf(service_res), 200);
    }


    @ResponseBody
    @RequestMapping(value = "/getScope", method = RequestMethod.POST)
    public ListResult getScope(Clientele arg) {
        String[] ids = arg.getComName().split(",");
        List<String> arrayList = new ArrayList<String>(Arrays.asList(ids));
        List<Goods> service_res = goodsService.selectByIds(arrayList);
        return new ListResult(true, service_res);
    }

    /**
     * create
     *
     * @param arg
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/create", method = RequestMethod.POST)
    public BaseResult<Object> insert(Clientele arg, HttpSession session) {
        SalePersonVo sale = (SalePersonVo) session.getAttribute("current");
        if (sale == null) {
            return new BaseResult(false, "未登录!", 401);
        }
        arg.setSalesId(String.valueOf(sale.getId())); // 限定某人名下用户
        SalePerson sp = new SalePerson();
        sp.setId(sale.getId());
        if (sale.getCustomerCount() == null) { // 我的客户累加1
//            sp.setCustomerCount(1);
        } else {
//            sp.setCustomerCount(sale.getCustomerCount() + 1);
        }
        spService.updateByPrimaryKeySelective(sp);
        arg.setComName(arg.getComName().trim());
        arg.setUnitCode(arg.getUnitCode().trim());
        Clientele clienteleExist = dataService.selectByComNameAndUnitCode(arg); // 客户已存在判断
        if (clienteleExist != null) {
            return new BaseResult(false, "销售名下已经存在该客户!", 403);
        }
        session.setAttribute(Constants.CURRENT_SP, salePersonMapper.selectByPrimaryKey(sp.getId()));// 更新session
        int service_res = dataService.insertSelective(arg);
        Address a = new Address() ;
        a.setFax(arg.getFax());
        a.setOwnerid(String.valueOf(arg.getId()));
        a.setPerson(arg.getPerson());
        a.setPhone(arg.getPhone());
        a.setDetail(arg.getAddress());
        get(a); // 保存地址
        return new BaseResult(true, service_res);
    }

    /**
     * update
     *
     * @param arg
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/update", method = RequestMethod.POST)
    public BaseResult<Integer> update(Clientele arg) {
        arg.setStatus("0"); //修改信息重新申请
        int service_res = dataService.updateByPrimaryKeySelective(arg);
        BaseResult<Integer> res = new BaseResult<Integer>(true, service_res);
        return res;
    }

    @ResponseBody
    @RequestMapping(value = "/delete", method = RequestMethod.POST)
    public BaseResult<Integer> delete(Clientele arg, HttpSession session) {
        arg.setStatus("-1");
        SalePerson sp = (SalePerson) session.getAttribute(Constants.CURRENT_SP);
        if (sp == null) {
            return new BaseResult(false, "未登录!", 403);
        }
        OrderVo ov = new OrderVo();
        ov.setClienteleId(arg.getId().toString());
        int count = orderService.queryCount(ov);
        if (count > 0) {
            return new BaseResult<Integer>(false, "该客户有订单数据，不能删除!", 500);
        }
//        dataService.queryCount(arg.)
        //
        SalePerson sp_ = new SalePerson();
        sp_.setId(sp.getId());
//        sp_.setCustomerCount((sp.getCustomerCount() - 1 > 0) ? (sp.getCustomerCount() - 1) : 0);
        spService.updateByPrimaryKeySelective(sp_);
  //      sp.setCustomerCount((sp.getCustomerCount() - 1 > 0) ? (sp.getCustomerCount() - 1) : 0);
        session.setAttribute(Constants.CURRENT_SP, sp);
        int service_res = dataService.updateByPrimaryKeySelective(arg);
        BaseResult<Integer> res = new BaseResult<Integer>(true, service_res);
        return res;
    }

    /***
     * 分页查询
     * @param arg
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/query", method = RequestMethod.GET)
    public ListResult<Object> query(ClienteleVo arg, HttpSession session) {
        SalePerson ps = (SalePerson) session.getAttribute(Constants.CURRENT_SP);
        if (ps == null) {
            return new ListResult(false, "未登录!", 401);
        }

        arg.setSalesId(String.valueOf(ps.getId()));
        List<Clientele> list = dataService.queryByPage(arg);
        int total = dataService.queryCount(arg);
        Pagination page = new Pagination(arg.getPage(), total, arg.getSize());
        ListResult<Object> res = new ListResult(true, list);
        res.setPage(page);
        return res;
    }


    /**
     * @param arg
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/queryMyClientele", method = RequestMethod.GET)
    public ListResult<Object> queryMyClientele(ClienteleVo arg, HttpSession session) {
        SalePerson sale = (SalePerson) session.getAttribute("current");
        ListResult<Object> res = null;
        if (sale != null) {
            arg.setSalesId(String.valueOf(sale.getId()));
            List<Clientele> list = dataService.queryMyClientele(arg);
            res = new ListResult(true, list);
        } else {
            res = new ListResult(false, "请登录!", 401);
        }
        return res;
    }
}
